import axios from 'axios'

const baseUrl = '/api'

// 封装axios
class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl
  }
  getInsideConfig() {
    const config = {
      baseUrl: this.baseUrl,
      header: []
    }
    return config
  }
  interception(instance) {
    // 请求拦截器
    instance.interceptors.request.use(
      (config) => {
        // 若有token，就在头部加上token
        if (localStorage.getItem('token')) {
          config.headers['Authorization'] =
            'Bearer' + localStorage.getItem('token')
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )
    // 响应拦截器
    instance.interceptors.response.use((response) => {
      const { status, data } = response
      if (status >= 200 && status < 300) {
        return data
      } else {
        // 401 未授权，跳转到登录页
        if (status === 401) {
          // 跳转到登录页
          this.$router.push('/login')
        }
        return Promise.reject(data)
      }
    })
  }
  request(options) {
    options = { ...this.getInsideConfig(), ...options }
    // 创建axios
    const instance = axios.create(options)
    this.interception(instance)
    return instance(options)
  }
}
export default new HttpRequest(baseUrl)
